//
//  TableViewCellButtonClickViewController.swift
//  iOS-RxSwift-Tutorials_Example
//
//  Created by mengru.tian on 2020/9/24.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift

class TableViewCellButtonClickViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "55.订阅UITableViewCell里的按钮点击事件"
        view.backgroundColor = .white
        
        test()
    }
    
    func test() {
        
        //创建一个重用的单元格
        tableView.register(UINib(nibName: "TableViewButtonCell", bundle: nil), forCellReuseIdentifier: "Cell")
        //单元格无法选中
        tableView.allowsSelection = false
        //初始化数据
        let items = Observable.just([
            "文本输入框的用法",
            "开关按钮的用法",
            "进度条的用法",
            "文本标签的用法",
            ])
        //设置单元格数据（其实就是对 cellForRowAt 的封装）
        items
            .bind(to: tableView.rx.items) { (tableView, row, element) in
                //初始化cell
                let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
                    as! TableViewButtonCell
                cell.textLabel?.text = "\(element)"
                 
                //cell中按钮点击事件订阅
                cell.button.rx.tap.asDriver()
                    .drive(onNext: { [weak self] in
                        self?.showAlert(title: "\(row)", message: element)
                    }).disposed(by: cell.disposeBag)
                 
                return cell
            }
            .disposed(by: disposeBag)
    }
    
    //显示弹出框信息
    func showAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message,
                                      preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .cancel))
        self.present(alert, animated: true)
    }

}
